/* ****************************************************************************
 *
 * Copyright (c) Microsoft Corporation. 
 *
 * This source code is subject to terms and conditions of the Microsoft Public License. A 
 * copy of the license can be found in the License.html file at the root of this distribution. If 
 * you cannot locate the  Microsoft Public License, please send an email to 
 * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound 
 * by the terms of the Microsoft Public License.
 *
 * You must not remove this notice, or any other, from this software.
 *
 * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
 * PARTICULAR PURPOSE.
 * ***************************************************************************/


#include "stdafx.h"
#include <pgl/algotools/Singleton.h>

namespace singletons
{

CDestructionManager::DestructionManagerPtr& CDestructionManager::GetInstance() 
{
	static DestructionManagerPtr the_singleton(new CDestructionManager);
	if (the_singleton.get() == NULL)
		throw _T("Could not create Destruction Manager");

	return the_singleton;
}

CDestructionManager::~CDestructionManager() 
{
	for (size_t i = 0; i < m_destructors.size(); ++i)
		delete m_destructors[i];
}

template <class T> class TGreaterPtr 
{
public:
	typedef T* T_ptr;
	bool operator()(const T_ptr& lhs, const T_ptr& rhs) const
	{ return *lhs > *rhs; };
};

void CDestructionManager::DestroyObjects() 
{
	// sort the destructors in decreasing order
	std::sort(m_destructors.begin(), m_destructors.end(),TGreaterPtr<CDestructor>());
	// destroy the objects
	for (size_t i = 0; i < m_destructors.size(); ++i)
	{
		m_destructors[i]->Destroy();
	}
};

};
